var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/grid/ImportExcel.tsx
var ImportExcel_exports = {};
__export(ImportExcel_exports, {
  ImportGrid: () => ImportGrid
});
module.exports = __toCommonJS(ImportExcel_exports);
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_xlsx = require("xlsx");
var import_baseComponent = require("../../baseComponent");
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var import_grid = require("./grid");
var statusText = ["选择需要导入的Excel文件", "正在读取文件内容...", "读取文件失败"];
var InternalImportGrid = (0, import_util.compHoc)((props) => {
  const {
    header,
    outRef,
    request,
    pagination,
    subTable,
    topArea,
    onSheetDataChange,
    isTree,
    expandCfg,
    defaultExpand,
    response,
    style,
    columns,
    convertData,
    mergeSplit = true,
    ...others
  } = props;
  const headerIndex = header.index ?? -1;
  const dataIndexRef = (0, import_react.useRef)({});
  const sheetDataRef = (0, import_react.useRef)({});
  const uploadRef = (0, import_react.useRef)();
  const keyRef = (0, import_react.useRef)((/* @__PURE__ */ new Date()).valueOf());
  const [upload, setUpload] = (0, import_react.useState)({ file: null, status: 0 });
  const [gridProps, setGridProps] = (0, import_react.useState)({ columns, dataSource: [] });
  const [sheets, setSheets] = (0, import_react.useState)([]);
  const [sheet, setSheet] = (0, import_react.useState)({
    changed: false
  });
  const headerSourceCallback = (0, import_util.useRefCallback)((index) => {
    return new Promise((resolve) => {
      if (import_util.iup.isFunction(header.source)) {
        resolve(header.source(index));
      } else {
        resolve(header.source || []);
      }
    });
  });
  const convertDataCallback = (0, import_util.useRefCallback)((n) => {
    return convertData ? convertData(n) : n;
  });
  const splitCallback = (0, import_util.useRefCallback)((r, c, m) => {
    if (import_util.iup.isBoolean(mergeSplit)) {
      return mergeSplit;
    } else {
      if (mergeSplit === "row") {
        return r === m.s.r;
      } else if (mergeSplit === "column") {
        return c === m.s.c;
      }
    }
    return true;
  });
  const dealSheetData = (0, import_util.useRefCallback)((bindFields) => {
    var _a;
    const sheetData = sheetDataRef.current[((_a = sheet.current) == null ? void 0 : _a.label) || ""];
    if (sheetData) {
      const dataArray = import_xlsx.utils.sheet_to_json(sheetData, { header: "A", defval: "" });
      let xlsColumns = [];
      let headerTitle = {};
      if (dataArray.length > 0) {
        xlsColumns = Object.keys(dataArray[0]);
        const merges = sheetData["!merges"] || [];
        const mergeCell = {};
        merges.forEach((m) => {
          var _a2;
          const mergeValue = ((_a2 = dataArray.find((d) => d.__rowNum__ === m.s.r)) == null ? void 0 : _a2[xlsColumns[m.s.c]]) ?? "";
          for (let r = m.s.r; r <= m.e.r; r++) {
            for (let c = m.s.c; c <= m.e.c; c++) {
              if (splitCallback(r, c, m)) {
                mergeCell[`${r}:${c}`] = mergeValue;
              }
            }
          }
        });
        dataArray.forEach((data) => {
          xlsColumns.forEach((k, i) => {
            const cell = `${data.__rowNum__}:${i}`;
            if (mergeCell.hasOwnProperty(cell)) {
              data[k] = mergeCell[cell];
            }
            if (import_util.iup.isDate(data[k])) {
              data[k] = import_util.iup.addDate(data[k], 43, "seconds", "YYYY-MM-DD HH:mm");
            }
          });
        });
        if (headerIndex > -1 && headerIndex < dataArray.length) {
          headerTitle = dataArray[headerIndex];
          dataArray.splice(headerIndex, 1);
        }
      }
      setGridProps((prev) => {
        var _a2;
        return {
          ...prev,
          columns: generateColumns({
            bindFields: bindFields ?? header.bindFields,
            defaultColumns: columns || [],
            columnArray: xlsColumns.map((k) => {
              return { dataIndex: k, title: headerTitle[k] || k, width: header.width ?? 100 };
            }),
            headerSource: headerSourceCallback(sheet.current.value),
            onChange: header.onChange,
            key: `${keyRef.current}_${(_a2 = sheet.current) == null ? void 0 : _a2.value}`,
            dataIndexRef
          }),
          dataSource: convertDataCallback(dataArray)
        };
      });
    }
  });
  const readExcel = (file) => {
    setUpload((prev) => ({ ...prev, status: 1 }));
    const fileReader = new FileReader();
    fileReader.onload = ({ target }) => {
      var _a, _b;
      const workbook = (0, import_xlsx.read)(target == null ? void 0 : target.result, { type: "binary", cellDates: true });
      sheetDataRef.current = workbook.Sheets;
      keyRef.current = (/* @__PURE__ */ new Date()).valueOf();
      const sheetNames = ((_b = (_a = workbook.Workbook) == null ? void 0 : _a.Sheets) == null ? void 0 : _b.filter((s) => s.Hidden === 0).map(({ name }) => name)) || workbook.SheetNames;
      const sheetOptions = sheetNames.map((label, index) => ({ value: index, label }));
      import_util.iup.batchedUpdates(() => {
        setUpload((prev) => ({ ...prev, status: 3, file }));
        setSheets(sheetOptions);
        setSheet({ changed: true, current: sheetOptions[0] });
      });
    };
    fileReader.onerror = () => {
      setUpload((prev) => ({ ...prev, status: 2 }));
    };
    fileReader.readAsBinaryString(file);
  };
  (0, import_util.useExtendRef)(outRef, {
    getImportDataIndexRef() {
      return dataIndexRef.current;
    },
    getImportBindFields() {
      const bindFields = {};
      Object.keys(dataIndexRef.current).forEach((k) => {
        const tmp = dataIndexRef.current[k];
        if (tmp !== k) {
          bindFields[k] = tmp;
        }
      });
      return bindFields;
    },
    getImportData() {
      const keys = Object.keys(dataIndexRef.current);
      return outRef.current.getApi().getRows().map(
        (r) => keys.reduce((p, c) => {
          if (c !== dataIndexRef.current[c]) {
            const tmp = { ...p, [dataIndexRef.current[c]]: r[c] };
            delete tmp[c];
            return tmp;
          }
          return p;
        }, r)
      );
    },
    refreshHeaderSource(options = {}) {
      const { bindFields } = options;
      keyRef.current = (/* @__PURE__ */ new Date()).valueOf();
      dealSheetData(bindFields);
    },
    importFile: readExcel,
    getUpload() {
      return uploadRef.current;
    }
  });
  (0, import_react.useEffect)(() => {
    dealSheetData();
  }, [sheet.current, columns]);
  (0, import_react.useEffect)(() => {
    if (sheet.current && sheet.changed) {
      sheet.changed = false;
      onSheetDataChange == null ? void 0 : onSheetDataChange(gridProps.dataSource, sheet.current);
    }
  }, [gridProps]);
  const onSheetChange = (0, import_util.useRefCallback)((value) => {
    setSheet({ changed: true, current: value });
  });
  const uploadProps = {
    ref: uploadRef,
    disabled: upload.status === 1,
    maxCount: 1,
    accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/vnd.ms-excel.sheet.macroEnabled.12",
    beforeUpload: (file) => {
      setSheets([]);
      readExcel(file);
      return import_antd.Upload.LIST_IGNORE;
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(import_util.Layout, { style }, /* @__PURE__ */ import_react.default.createElement(import_util.Layout, { direction: "row", center: true, style: { padding: "6px 0" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Upload, { ...uploadProps }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      loading: upload.status === 1,
      className: "nowrap",
      title: statusText[upload.status] || upload.file.name,
      style: { color: `${upload.status === 2 ? "red" : ""}`, maxWidth: 300 }
    },
    statusText[upload.status] || upload.file.name
  )), sheets.length > 1 && /* @__PURE__ */ import_react.default.createElement(
    import_baseComponent.Select,
    {
      defaultValue: sheets[0],
      options: sheets,
      style: { minWidth: 80, marginLeft: 10 },
      onChange: onSheetChange,
      placeholder: "请选择Sheet页"
    }
  ), /* @__PURE__ */ import_react.default.createElement(import_util.Layout.Flex, null, topArea)), /* @__PURE__ */ import_react.default.createElement(import_util.Layout.Flex, null, /* @__PURE__ */ import_react.default.createElement(import_grid.Grid, { bordered: true, showRowNumber: true, ref: outRef, ...others, ...gridProps, headerMenu: false })));
});
var ImportGrid = InternalImportGrid;
ImportGrid.xlsx = { utils: import_xlsx.utils, read: import_xlsx.read };
ImportGrid.modal = ({ gridProps, ...others }) => {
  return new Promise((resolve) => {
    (0, import_functionalComponent.showModal)({
      title: "Excel导入",
      width: 860,
      height: 600,
      // 设置高度开启拖拽调整大小功能
      ...others,
      content: /* @__PURE__ */ import_react.default.createElement(Content, { ...gridProps }),
      async onOk(ins) {
        var _a;
        const importGrid = ins.getApi().getGrid();
        if (await ((_a = others.onOk) == null ? void 0 : _a.call(others, ins, importGrid)) !== false) {
          const excelData = importGrid.getImportData();
          ins.destroy();
          resolve([true, excelData]);
        }
      },
      async onCancel(ins) {
        var _a;
        if (await ((_a = others.onCancel) == null ? void 0 : _a.call(others, ins, ins.getApi().getGrid())) !== false) {
          ins.destroy();
          resolve([false, []]);
        }
      }
    });
  });
};
function Content(props) {
  const ref = (0, import_react.useRef)();
  const { ins } = (0, import_react.useContext)(import_functionalComponent.ModalContext);
  (0, import_react.useEffect)(() => {
    ins.setApi({
      getGrid() {
        return ref.current.getApi();
      }
    });
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(ImportGrid, { ...props, style: { padding: "0 6px", ...props.style }, ref });
}
function generateColumns({ bindFields, defaultColumns, columnArray, headerSource, onChange, dataIndexRef, key }) {
  const selectProps = {
    fitHeight: true,
    variant: "borderless",
    style: { width: "100%", height: "100%", textAlign: "left", fontWeight: "normal" },
    request: async () => {
      return await headerSource;
    }
  };
  const selectedMap = /* @__PURE__ */ new Map();
  dataIndexRef.current = {};
  const getGroupIn = (dataIndex) => () => {
    dataIndexRef.current[dataIndex] = (bindFields == null ? void 0 : bindFields[dataIndex]) || dataIndex;
    const selectRef = import_react.default.createRef();
    const onSelectChange = (value) => {
      var _a;
      if (value === null) {
        dataIndexRef.current[dataIndex] = dataIndex;
        return;
      }
      const lastValue = dataIndexRef.current[dataIndex];
      dataIndexRef.current[dataIndex] = value;
      if (selectedMap.has(value)) {
        const [lastSelectRef, lastDataIndex] = selectedMap.get(value);
        dataIndexRef.current[lastDataIndex] = lastDataIndex;
        (_a = lastSelectRef.current) == null ? void 0 : _a.getApi().setValue(null);
      }
      selectedMap.has(lastValue) && selectedMap.delete(lastValue);
      selectedMap.set(value, [selectRef, dataIndex]);
      onChange == null ? void 0 : onChange({ dataIndex, value });
    };
    const defaultValue = bindFields == null ? void 0 : bindFields[dataIndex];
    defaultValue && selectedMap.set(defaultValue, [selectRef, dataIndex]);
    return /* @__PURE__ */ import_react.default.createElement(
      import_baseComponent.Select,
      {
        key: `${key}_${dataIndex}`,
        ...selectProps,
        defaultValue,
        ref: selectRef,
        labelInValue: false,
        placeholder: `选择对应字段`,
        onChange: onSelectChange
      }
    );
  };
  return [
    ...defaultColumns,
    ...columnArray.map(({ dataIndex, title, width }) => {
      return {
        dataIndex,
        title,
        width,
        flex: 1,
        groupIn: [getGroupIn(dataIndex)]
      };
    })
  ];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ImportGrid
});
